package activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.laoxinwen.app.R;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import activity.main.MainActivity;
import bean.wraper.DefaultStringWrapper;
import common.BaseActivity;
import common.Constants;
import common.HttpCallBack;
import common.Requester;
import util.LogicUtil;
import util.NetUtil;
import util.ToastUtil;

/**
 * Created by ilioili on 2015/1/3.
 */
public class CommentActivity extends BaseActivity implements AMapLocationListener {
    final public static String INTENT_KEY_NEWSGROUP_ID = "1";
    final public static String INTENT_KEY_COMMENT_ID = "2";
    final public static String INTENT_KEY_NEWS_ID = "3";
    final public static String INTENT_KEY_ARTICLE_ID = "4";
    public static final String ACTION_REQUEST_FOCUS = "RequestFocus";
    private static final int TYPE_VOTE = 1;
    private static final int TYPE_REPLY = 2;
    private static final int TYPE_COPY = 3;
    private static final int TYPE_RELOAD = 4;
    private static final int TYPE_TARGET = 5;
    private String articleId;
    private String referCommentId;
    @id(R.id.et_content)
    EditText etContent;
    @id(R.id.iv_loading)
    private ProgressBar ivLoading;
    private String newsId;
    private int referId;
    private String replyContent;
    private String topicId;
    private String url;
    private WebView webView;
    private LocationManagerProxy locationManagerProxy;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == TYPE_RELOAD) {
                if (NetUtil.isNetworkConnected(CommentActivity.this)) {
                    loadUrl();
                } else {
                    showToast(Constants.MSG_NET_ERROR);
                }

            } else if (msg.what == TYPE_COPY) {
                showToast("已复制到系统剪切板");
            } else {
                try {
                    final JSONObject inputData = new JSONObject(msg.obj.toString());
                    switch (msg.what) {
                        case TYPE_REPLY:
                            referCommentId = inputData.getString("id");
                            etContent.requestFocus();
                            showInputKeyboard(etContent);
                            break;
                        case TYPE_VOTE:
                            Requester.vote(inputData.getString("id"), new HttpCallBack<DefaultStringWrapper>() {
                                @Override
                                public void onSucceed(DefaultStringWrapper data) {
                                    try {
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("commentId", inputData.getString("id"));
                                        webView.loadUrl("javascript:voteSuccess(" + jsonObject.toString() + ")");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                }
                            });
                            break;
                        case TYPE_TARGET:
                            String type = inputData.getString("type");
                            String id = inputData.getString("id");
                            Intent it = "news".equals(type) ? NewsActivity.getIntent(CommentActivity.this, id) : ArticleActivity.getIntent(CommentActivity.this, id);
                            startActivity(it);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public static Intent getIntent(Context context, String newsGrupId, String commentId, String newsId, String articleId) {
        Intent it = new Intent(context, CommentActivity.class);
        it.putExtra(INTENT_KEY_NEWSGROUP_ID, newsGrupId);
        it.putExtra(INTENT_KEY_COMMENT_ID, commentId);
        it.putExtra(INTENT_KEY_ARTICLE_ID, articleId);
        it.putExtra(INTENT_KEY_NEWS_ID, newsId);
        return it;
    }

    @Override
    public void finish() {
        if (this.isTaskRoot()) {
            Intent it = new Intent(this, MainActivity.class);
            startActivity(it);
        }
        super.finish();
    }

    @SuppressLint("JavascriptInterface")
    private void loadErrorHtml() {
        webView.clearHistory();
        webView.loadUrl("file:///android_asset/loadfail.html");
        webView.addJavascriptInterface(new Object() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @JavascriptInterface
            public void jsreload(String content) {
                handler.sendEmptyMessage(TYPE_RELOAD);
            }
        }, "Android");
    }

    @SuppressLint("JavascriptInterface")
    private void loadUrl() {
        webView.clearHistory();
        webView.loadUrl(url);
        webView.addJavascriptInterface(new Object() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @JavascriptInterface
            public void jscopy(String content) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    try {
                        JSONObject jsonObject = new JSONObject(content);
                        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, jsonObject.getString("content")));
                        handler.sendEmptyMessage(TYPE_COPY);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

            @JavascriptInterface
            public void jsreply(String content) {
                handler.obtainMessage(TYPE_REPLY, content).sendToTarget();
            }

            @JavascriptInterface
            public void jsvote(String content) {
                handler.obtainMessage(TYPE_VOTE, content).sendToTarget();
            }

            @JavascriptInterface
            public void jstarget(String content) {
                handler.obtainMessage(TYPE_TARGET, content).sendToTarget();
            }
        }, "Android");

    }

    @Override
    public void onClick(final View view) {
        hideInputKeyboard();
        switch (view.getId()) {
            case R.id.bt_share:
                break;
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_comment:
                view.setEnabled(false);
                String content = etContent.getText().toString().trim();
                if (em(content)) {
                    ToastUtil.showShortToast(this, "请填写评论内容哦");
                    return;
                }
                referCommentId = null == referCommentId ? "" : referCommentId;
                //位置
                String location = "";
                AMapLocation aMapLocation = locationManagerProxy.getLastKnownLocation(LocationProviderProxy.AMapNetwork);
                if(aMapLocation != null && aMapLocation.getAMapException().getErrorCode() == 0){
                    //获取位置信息
                    Double lng = aMapLocation.getLongitude();
                    Double lat = aMapLocation.getLatitude();
                    String provCity = (aMapLocation.getProvince() == null ? "" : aMapLocation.getProvince()) + aMapLocation.getCity();
                    String addr = aMapLocation.getAddress();
                    location = lng + "|" + lat + "|" + provCity + "|" + addr;
                }
                Requester.comment(content, newsId, articleId, topicId, referCommentId, location, new HttpCallBack<DefaultStringWrapper>() {
                    @Override
                    protected void onNetError() {
                        super.onNetError();
                        view.setEnabled(true);
                    }

                    @Override
                    protected void onServerError(DefaultStringWrapper data) {
                        super.onServerError(data);
                        view.setEnabled(true);
                    }

                    @Override
                    public void onSucceed(DefaultStringWrapper data) {
                        try {
                            hideInputKeyboard();
                            ToastUtil.showShortToast(CommentActivity.this, "评论成功");
                            etContent.setText(null);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("content", data.getData());
                            webView.loadUrl("javascript:commentSuccess(" + jsonObject.toString() + ")");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        view.setEnabled(true);

                    }
                });
                break;
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        loadView();
        setWebView();
        topicId = getIntent().getStringExtra(INTENT_KEY_NEWSGROUP_ID);
        referCommentId = getIntent().getStringExtra(INTENT_KEY_COMMENT_ID);
        newsId = getIntent().getStringExtra(INTENT_KEY_NEWS_ID);
        articleId = getIntent().getStringExtra(INTENT_KEY_ARTICLE_ID);
        if (ACTION_REQUEST_FOCUS.equals(getIntent().getAction())) {
            etContent.requestFocus();
        }

        url = LogicUtil.getCommentsUrl(topicId, newsId, articleId, referCommentId);
        loadUrl();
        //初始化高德定位
        locationManagerProxy = LocationManagerProxy.getInstance(this);
        locationManagerProxy.setGpsEnable(false);
        locationManagerProxy.requestLocationData(LocationProviderProxy.AMapNetwork, -1, 15, this);
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationManagerProxy.removeUpdates(this);
        locationManagerProxy.destroy();
    }

    @Override
    protected void onRightSlide() {
        finish();
    }

    /**
     * 新闻：http://www.laoxinwen.com/comments/news/7368jlkg?app=v*
     * 文章：http://www.laoxinwen.com/comments/article/7368jlkg?app=v*
     */

    @SuppressLint({"SetJavaScriptEnabled", "NewApi"})
    private void setWebView() {
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                cancelLoading();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoading();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (!Constants.ERROR_HTML.equals(failingUrl)) {
                    loadErrorHtml();
                }
            }
        });
        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);
        webView.setBackgroundColor(Color.TRANSPARENT);
        WebSettings webSettings = webView.getSettings();

                webSettings.setUseWideViewPort(true);
        //        if (android.os.Build.VERSION.SDK_INT > 10) {
        //            webSettings.setDisplayZoomControls(false);//隐藏缩放按钮
        //        }
        //        webSettings.setBuiltInZoomControls(false);
        //        webSettings.setLoadWithOverviewMode(true);
        //        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setJavaScriptEnabled(true);
        //        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹出窗口
    }

    private void showLoading() {
        ivLoading.setVisibility(View.VISIBLE);
    }

    private void cancelLoading() {
        ivLoading.setVisibility(View.GONE);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("评论页");
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("评论页");
    }
}
